﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.FileProviders;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Core.StaticFileRegistService
{
    /// <summary>
    /// 静态文件配置类
    /// </summary>
    public static class StaticFileConfig
    {
        /// <summary>
        /// 静态文件映射的物理路径和请求路径（每多一个就往里面加入一个值就行）
        /// </summary>
        public static Dictionary<string, string> FilePathAndRequestPath = new Dictionary<string, string>()
        {
            {"flv","flv" }
        };
        /// <summary>
        /// 使用静态文件注入方法
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public static void UseStaticFilesConfig(this IApplicationBuilder app, IWebHostEnvironment env)
        {
            string PhysicalPath=string.Empty;
            foreach (var item in FilePathAndRequestPath)
            {
                if (item.Key.Contains(":"))
                {
                    PhysicalPath = item.Key;
                }
                else
                {
                    PhysicalPath = Path.Combine(env.ContentRootPath, item.Key.Trim('/'));
                }
                if (!Directory.Exists(PhysicalPath))
                {
                    Directory.CreateDirectory(PhysicalPath);
                }
                app.UseStaticFiles(new StaticFileOptions()
                {
                    FileProvider=new PhysicalFileProvider(PhysicalPath),
                    RequestPath=item.Value.StartsWith("/")? item.Value:"/"+ item.Value
                });
            }
        }
    }
}
